package com.zly.framework.rbac.handler.success;

import com.alibaba.fastjson2.JSON;
import com.zly.framework.rbac.configuration.SysAuthConfiguration;
import com.zly.framework.rbac.utils.JwtUtils;
import com.zly.framework.rbac.model.vo.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;

@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysAuthConfiguration sysAuthConfiguration;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        log.info("登录成功:{}", authentication.getName());
        String token = jwtUtils.generateToken(authentication.getName(), (Collection<GrantedAuthority>) authentication.getAuthorities());
        String REDIS_PREFIX = "user:";
        String REDIS_KEY = REDIS_PREFIX + authentication.getName();
        Long size = stringRedisTemplate.opsForList().size(REDIS_KEY);
        if (size == null || size < sysAuthConfiguration.getUser().getMax()) {
            stringRedisTemplate.opsForList().leftPush(REDIS_KEY, token);
        } else {
            stringRedisTemplate.opsForList().rightPop(REDIS_KEY);
            stringRedisTemplate.opsForList().leftPush(REDIS_KEY, token);
        }
        response.getWriter().write(JSON.toJSONString(Result.SUCCESS(token)));
    }
}
